//
//  ResourceDetailViewController.m
//  CareGiver
//
//  Created by Guillermo Moral on 8/17/14.
//  Copyright (c) 2014 Humana. All rights reserved.
//

#import "ResourceDetailViewController.h"
#import <AddressBook/AddressBook.h>

@interface ResourceDetailViewController ()

@property(nonatomic, strong)ResourceModel *currentResource;

@end

static NSString *ResourceIdentifier = @"resourceAnnotationIdentifier";

@implementation ResourceDetailViewController


+ (CGFloat)annotationPadding;
{
    return 10.0f;
}

+ (CGFloat)calloutHeight;
{
    return 40.0f;
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.mapView.mapType = MKMapTypeHybrid;
}

- (void)viewWillAppear:(BOOL)animated {
    
    [self updateMap];
    
    self.organizationTitle.text = @"Coca Cola";
    
    ECPhoneNumberFormatter *formatter = [[ECPhoneNumberFormatter alloc] init];
    NSString *formattedNumber = [formatter stringForObjectValue:@"2345677890"];
    self.organizationTitle.text = formattedNumber;
}

// Monday - Friday - 7:30 AM - 5 PM

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)gotoLocation
{
    // start off by default in San Francisco
    MKCoordinateRegion newRegion;
    newRegion.center.latitude = [self.currentResource.latitude doubleValue];
    newRegion.center.longitude = [self.currentResource.longitude doubleValue];
    newRegion.span.latitudeDelta = 0.112872;
    newRegion.span.longitudeDelta = 0.109863;
    
    [self.mapView setRegion:newRegion animated:YES];
}

-(void)updateMap {
    [self gotoLocation];
    [self.mapView removeAnnotations:self.mapView.annotations];
    [self.mapView addAnnotations:self.resourcesAnnotations];
}

-(void)updateCurrentLocation:(ResourceModel*)resourceModel {
    self.resourcesAnnotations = [[NSMutableArray alloc]initWithCapacity:1];
    self.currentResource = resourceModel;
    [self.resourcesAnnotations addObject:self.currentResource];
}

#pragma mark - MKMapViewDelegate

- (void)mapView:(MKMapView *)mapView annotationView:(MKAnnotationView *)view calloutAccessoryControlTapped:(UIControl *)control
{
    id <MKAnnotation> annotation = [view annotation];
    
    if ([annotation isKindOfClass:[ResourceModel class]])
    {
        NSLog(@"clicked annotation");
    }
}

- (MKAnnotationView *)mapView:(MKMapView *)theMapView viewForAnnotation:(id <MKAnnotation>)annotation
{
    // in case it's the user location, we already have an annotation, so just return nil
    if ([annotation isKindOfClass:[MKUserLocation class]])
    {
        return nil;
    }
    
    if ([annotation isKindOfClass:[ResourceModel class]])
    {
        MKAnnotationView *flagAnnotationView =  [self.mapView dequeueReusableAnnotationViewWithIdentifier:ResourceIdentifier];
        
        if (flagAnnotationView == nil)
        {
            MKAnnotationView *annotationView = [[MKAnnotationView alloc] initWithAnnotation:annotation
                                                                            reuseIdentifier:ResourceIdentifier];
            annotationView.canShowCallout = YES;
            
            UIImage *flagImage = [UIImage imageNamed:@"Point.png"];
            
            annotationView.image = flagImage;
            annotationView.opaque = NO;
            
            // offset the flag annotation so that the flag pole rests on the map coordinate
            annotationView.centerOffset = CGPointMake( annotationView.centerOffset.x + annotationView.image.size.width/2, annotationView.centerOffset.y - annotationView.image.size.height/2 );
            
            return annotationView;
        }
        else
        {
            flagAnnotationView.annotation = annotation;
        }
        return flagAnnotationView;
    }
    
    return nil;
}
- (BOOL)textView:(UITextView *)textView shouldInteractWithURL:(NSURL *)URL inRange:(NSRange)characterRange NS_AVAILABLE_IOS(7_0) {
    
    [textView setTintColor:[UIColor purpleColor]];
    return YES;
}

#pragma mark - Shared Contact

- (void)addContact
{
    ABAddressBookRef addressBook = NULL;
    CFErrorRef error = NULL;
    
    switch (ABAddressBookGetAuthorizationStatus()) {
            
        case kABAuthorizationStatusAuthorized: {
            addressBook = ABAddressBookCreateWithOptions(NULL, &error);
            
            [self addAccountWithFirstName:@"Guillermo" lastName:@"Moral" inAddressBook:addressBook];
            
            if (addressBook != NULL) CFRelease(addressBook);
            break;
        }
            
        case kABAuthorizationStatusDenied: {
            NSLog(@"Access denied to address book");
            break;
        }
            
        case kABAuthorizationStatusNotDetermined: {
            addressBook = ABAddressBookCreateWithOptions(NULL, &error);
            ABAddressBookRequestAccessWithCompletion(addressBook, ^(bool granted, CFErrorRef error) {
                if (granted) {
                    NSLog(@"Access was granted");
                    [self addAccountWithFirstName:@"Guillermo" lastName:@"Moral" inAddressBook:addressBook];
                }
                else NSLog(@"Access was not granted");
                if (addressBook != NULL) CFRelease(addressBook);
            });
            break;
        }
            
        case kABAuthorizationStatusRestricted: {
            NSLog(@"access restricted to address book");
            break;
        }
            
    }
}

- (ABRecordRef)addAccountWithFirstName:(NSString *)firstName lastName:(NSString *)lastName inAddressBook:(ABAddressBookRef)addressBook
{
    ABRecordRef result = NULL;
    CFErrorRef error = NULL;
    
    //1
    result = ABPersonCreate();
    if (result == NULL) {
        NSLog(@"Failed to create a new person.");
        return NULL;
    }
    
    //2
    BOOL couldSetFirstName = ABRecordSetValue(result, kABPersonFirstNameProperty, (__bridge CFTypeRef)firstName, &error);
    BOOL couldSetLastName = ABRecordSetValue(result, kABPersonLastNameProperty, (__bridge CFTypeRef)lastName, &error);
    
    if (couldSetFirstName && couldSetLastName) {
        NSLog(@"Successfully set the first name and the last name of the person.");
    } else {
        NSLog(@"Failed.");
    }
    
    //3
    BOOL couldAddPerson = ABAddressBookAddRecord(addressBook, result, &error);
    
    if (couldAddPerson) {
        NSLog(@"Successfully added the person.");
    } else {
        NSLog(@"Failed to add the person.");
        CFRelease(result);
        result = NULL;
        return result;
    }
    
    //4
    if (ABAddressBookHasUnsavedChanges(addressBook)) {
        BOOL couldSaveAddressBook = ABAddressBookSave(addressBook, &error);
        
        if (couldSaveAddressBook) {
            NSLog(@"Succesfully saved the address book.");
        } else {
            NSLog(@"Failed.");
        }
    }
    
    return result;
}

# pragma mark - Contact Delegate


- (IBAction)pressShareContact:(id)sender {
    UIActivityViewController *controller = [[UIActivityViewController alloc]initWithActivityItems:@[UIActivityTypeAssignToContact] applicationActivities:nil];
    [controller setValue:@"Que Fachemos" forKey:@"subject"];
    [self presentViewController:controller animated:YES completion:nil];
}


























@end
